package com.ruoyi.inspection.service;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.inspection.domain.GovernCheckTask;
import com.ruoyi.inspection.domain.GovernCheckTaskInfo;
import com.ruoyi.inspection.domain.GovernCheckTaskPlan;
import com.ruoyi.inspection.domain.GovernCheckTaskPlanItem;
import com.ruoyi.inspection.utils.IdFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service("taskService")
public class GovernTaskService {
    @Resource
    private GovernCheckTaskPlanService governCheckTaskPlanService;
    @Resource
    private GovernCheckTaskPlanItemService governCheckTaskPlanItemService;

    @Resource
    private GovernCheckTaskInfoService governCheckTaskInfoService;

    /**
     * 任务分解生成计划
     * @param plan
     * @return
     */
    @Transactional
    public int savePlan(GovernCheckTaskPlan plan){

        governCheckTaskPlanService.insert(plan);

        List<GovernCheckTaskPlanItem> itemList = plan.getGovernCheckTaskPlanItemList();
        for(GovernCheckTaskPlanItem planItem : itemList){
            planItem.setGovernTaskPlanId(plan.getGovernTaskPlanId());

            planItem.setGovernCheckTaskItemId(planItem.getGovernCheckTaskItemId());
            planItem.setGovernCheckTaskId(planItem.getGovernCheckTaskId());

            governCheckTaskPlanItemService.insert(planItem);
        }

        return 1;
    }

    /**
     * 计划编辑
     * @param plan
     * @return
     */
    @Transactional
    public int editPlan(GovernCheckTaskPlan plan){
        plan = governCheckTaskPlanService.queryById(plan.getGovernTaskPlanId());


        plan.setGovernUpdateDate(new Date());
        plan.setGovernUpdateBy(SecurityUtils.getUsername());
        governCheckTaskPlanService.update(plan);

        //先删除原有的
        governCheckTaskPlanItemService.deleteByGovernTaskPlanId(plan.getGovernTaskPlanId());

        List<GovernCheckTaskPlanItem> itemList = plan.getGovernCheckTaskPlanItemList();
        for(GovernCheckTaskPlanItem planItem : itemList){
            planItem.setGovernTaskPlanId(plan.getGovernTaskPlanId());
            planItem.setGovernTaskPlanItemId(IdFactory.newLongId());
            planItem.setGovernCheckTaskItemId(planItem.getGovernCheckTaskItemId());
            planItem.setGovernCheckTaskId(planItem.getGovernCheckTaskId());
            planItem.setGovernCreateDate(new Date());
            planItem.setGovernCreateBy(SecurityUtils.getUsername());
            governCheckTaskPlanItemService.insert(planItem);
        }

        return 1;
    }

}
